package com.um.jdy.platform.station.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.um.jdy.common.device.code.DeviceCode;
import com.um.jdy.common.device.entity.dto.StationDTO;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.entity.po.Station;
import com.um.jdy.common.device.entity.vo.StationVO;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.common.device.service.StationService;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.service.CompanyService;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.platform.station.entity.dto.EditStationDTO;
import com.um.jdy.platform.station.entity.vo.EditStationVO;
import com.um.jdy.platform.station.entity.vo.StationItemVO;
import com.um.jdy.platform.user.service.SessionUserService;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.BaseEntity;
import com.um.springboot.starter.orm.entity.BaseVO;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.JSONUtil;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 管理类：站场
 *
 * @author cs
 * 日期 2023/5/24
 * 版权所有 广州优匠科技有限公司
 */
@Component
public class StationManager extends BaseManager<StationService> {

    @Autowired
    CompanyService companyService;

    @Autowired
    SessionUserService companyUserService;

    @Autowired
    PileService pileService;

    @Autowired
    MerchantService merchantService;


    /**
     * 分页查询站场
     * @param params
     * @return
     */
    public Response<Page<StationItemVO>> getStationPage(PageParams params){
        Page page = new Page();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());

        params.getCondition().put("s.com_id",getComId());

        page = service.getCMSViewModelPageBySqlName(page, "get_station_page","get_station_count",StationItemVO.class,params.getProperties(), params.getValues(),params.getRangeEntitys(),params.getOrderNames(),params.getSortOns());

        return Response.success(page);
    }

    public Response<List<StationVO>> list() {
        List<Station> list = service.getList(new String[]{},new Object[]{},new String[]{"create_time"},new String[]{"desc"});
        return Response.success(UMBeanUtils.copyBeanList(list,StationVO.class));
    }

    public Response<List<StationVO>> listByMerchant(String id) {
        List<Station> list = service.getList(new String[]{"platform_merchant_id"},new Object[]{id},new String[]{"create_time"},new String[]{"desc"});
        return Response.success(UMBeanUtils.copyBeanList(list,StationVO.class));
    }

    public Response<EditStationVO> get(String id) {
        Station entity = service.getEntity(id);
        EditStationVO vo = UMBeanUtils.copyBean(entity, EditStationVO.class);
        if(!StringUtil.isEmpty(entity.getLabelItems()))
            vo.setLabelList(JSONUtil.parseJSONToList(entity.getLabelItems()));
        else
            vo.setLabelList(new ArrayList<>());

        if(!StringUtil.isEmpty(entity.getServiceItems()))
            vo.setServiceList(JSONUtil.parseJSONToList(entity.getServiceItems()));
        else
            vo.setServiceList(new ArrayList<>());
        return Response.success(vo);
    }


    @Transactional
    public Response<Station> addEntity(EditStationDTO dto) {
        //验证分账比例不超上级
        Merchant merchant = merchantService.getEntity(dto.getPlatformMerchantId());
        if(!StringUtil.getTrim(merchant.getParentId()).equals("")){
            Merchant agent = merchantService.getEntity(merchant.getParentId());
            if(agent != null && agent.getCommissionRate() < dto.getCommissionRate().intValue()){
                throw new ServiceException(PartnersCode.RateNotLargeThanParent);
            }
        }

        dto.setCreateTime(DateUtil.date());
        Station station = BeanUtil.toBean(dto, Station.class);
        station.setLabelItems(JSONUtil.toJSONString(dto.getLabelList()));
        station.setServiceItems(JSONUtil.toJSONString(dto.getServiceList()));
        station.setCreateUserId(companyUserService.getTokenUserId());
        //保存充电站
        service.save(station);
        return Response.success(station);
    }

    @Transactional
    public Response<Station> updateEntity(String id, EditStationDTO dto) {

        if (null == service.getEntity("device_station_id", id)) {
            throw new ServiceException(DeviceCode.NoStation);
        }

        //验证分账比例不超上级
        Merchant merchant = merchantService.getEntity(dto.getPlatformMerchantId());
        if(!StringUtil.getTrim(merchant.getParentId()).equals("")){
            Merchant agent = merchantService.getEntity(merchant.getParentId());
            if(agent != null && agent.getCommissionRate() < dto.getCommissionRate().intValue()){
                throw new ServiceException(PartnersCode.RateNotLargeThanParent);
            }
        }

        Station station = BeanUtil.toBean(dto, Station.class);
        station.setLabelItems(JSONUtil.toJSONString(dto.getLabelList()));
        station.setServiceItems(JSONUtil.toJSONString(dto.getServiceList()));
        station.setDeviceStationId(id);
        //保存充电站
        service.save(station);
        return Response.success(station);
    }

    public Response delete(String id) {
        boolean result = this.service.delete(id);
        recyclePiles(id);
        return result ? Response.success() : Response.failed();
    }

    @Transactional
    public Response deleteIds(List<String> ids) {
        boolean result = service.deleteIds(ids);
        ids.stream().forEach(id -> {
            recyclePiles(id);
        });
        return result ? Response.success() : Response.failed();
    }

    /**
     * 回收桩列表
     *
     * @param stationId
     */
    private void recyclePiles(String stationId) {
        List<Pile> piles = pileService.getList("device_station_id", stationId);
        piles.stream().forEach(pile -> {
            pile.setDeviceStationId("");
            pileService.update(pile);
        });
    }




}
